package com.hitnet.hitnet.pic;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.Toast;

import com.hitnet.hitnet.R;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
/**
 *
 * @author xuanli
 *
 */
public class MainActivity extends Activity
{//
	private ImageView back;
	private static final int RESULTE = 1;
	private HashMap<String, List<String>> mGruopMap = new HashMap<String, List<String>>();
	private List<ImageBean> list = new ArrayList<ImageBean>();
	private final static int SCAN_OK = 1;
	private ProgressDialog mProgressDialog;
	private GroupAdapter adapter;
	private GridView mGroupGridView;
	private List<String> mDrr = new ArrayList<String>();

	private Handler mHandler = new Handler()
	{

		@Override
		public void handleMessage(Message msg)
		{
			super.handleMessage(msg);
			switch (msg.what)
			{
			case SCAN_OK:
				// �رս����
				mProgressDialog.dismiss();

				adapter = new GroupAdapter(MainActivity.this, list = subGroupOfImage(mGruopMap), mGroupGridView);
				mGroupGridView.setAdapter(adapter);
				break;
			}
		}

	};

	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.choose_folder);

		mGroupGridView = (GridView) findViewById(R.id.main_grid);
		back = (ImageView)this.findViewById(R.id.comeBack);
		back.setOnClickListener(new back());
		getImages();

		mGroupGridView.setOnItemClickListener(new OnItemClickListener()
		{

			public void onItemClick(AdapterView<?> parent, View view, int position, long id)
			{
				List<String> childList = mGruopMap.get(list.get(position).getFolderName());

				Intent mIntent = new Intent(MainActivity.this, ShowImageActivity.class);
				mIntent.putExtra("dirName", list.get(position).getFolderName());
				mIntent.putStringArrayListExtra("data", (ArrayList<String>) childList);
				
				startActivityForResult(mIntent,RESULTE);

			}
		});
		ExitApplication.getInstance().addActivity(this); 
	}
	
	//
	class back implements OnClickListener{

		public void onClick(View arg0) {
			// TODO Auto-generated method stub
			NativeImageLoader.mSelectList.removeAll(NativeImageLoader.mSelectList);
			MainActivity.this.finish();
		}
		
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0)
		{
			NativeImageLoader.mSelectList.removeAll(NativeImageLoader.mSelectList);
		}
		return super.onKeyDown(keyCode, event);
	}

	/**
	 * acqure images
	 */
	private void getImages()
	{
		if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED))
		{
			Toast.makeText(this, "no such file", Toast.LENGTH_SHORT).show();
			return;
		}

		//
		mProgressDialog = ProgressDialog.show(this, null, "loading...");

        // open file storage and loading multi-media files
		new Thread(new Runnable()
		{

			public void run()
			{
				Uri mImageUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
				Uri videoUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
				ContentResolver mContentResolver = MainActivity.this.getContentResolver();
				// ֻthe type of file: jpeg,jpg, png
				Cursor mCursor = mContentResolver.query(mImageUri, null, MediaStore.Images.Media.MIME_TYPE + "=? or "
						+ MediaStore.Images.Media.MIME_TYPE + "=? or " + MediaStore.Images.Media.MIME_TYPE + "=?",
						new String[] { "image/jpeg", "image/png", "image/jpg" }, MediaStore.Images.Media.DATE_MODIFIED);

                Cursor videoCursor = mContentResolver.query(videoUri,null,null,null,MediaStore.Video.Media.DEFAULT_SORT_ORDER);

                //遍历图片文件，并分文件夹
				while (mCursor.moveToNext())
				{
					//
					String path = mCursor.getString(mCursor.getColumnIndex(MediaStore.Images.Media.DATA));
					// System.out.println(path);
					//
					String parentName = new File(path).getParentFile().getName();

					if (!mGruopMap.containsKey(parentName))
					{
						List<String> chileList = new ArrayList<String>();
						chileList.add(path);
						mGruopMap.put(parentName, chileList);
					} else
					{
						mGruopMap.get(parentName).add(path);
					}
				}

                //遍历视频文件，并分文件夹
                while (videoCursor.moveToNext()){
                    String path = videoCursor.getString(videoCursor.getColumnIndex(MediaStore.Video.Media.DATA));
                    String parentName = new File(path).getParentFile().getName();

                    if (!mGruopMap.containsKey(parentName)){
                        List<String> childList = new ArrayList<String>();
                        childList.add(path);
                        mGruopMap.put(parentName,childList);
                    }else{
                        mGruopMap.get(parentName).add(path);
                    }
                }

				mCursor.close();
                videoCursor.close();

				// Handler
				mHandler.sendEmptyMessage(SCAN_OK);

			}
		}).start();

	}

	/**

	 * 
	 * @param mGruopMap
	 * @return
	 */
	private List<ImageBean> subGroupOfImage(HashMap<String, List<String>> mGruopMap)
	{
		if (mGruopMap.size() == 0)
		{
			return null;
		}
		List<ImageBean> list = new ArrayList<ImageBean>();

		Iterator<Map.Entry<String, List<String>>> it = mGruopMap.entrySet().iterator();
		while (it.hasNext())
		{
			Map.Entry<String, List<String>> entry = it.next();
			ImageBean mImageBean = new ImageBean();
			String key = entry.getKey();
			List<String> value = entry.getValue();

			mImageBean.setFolderName(key);
			mImageBean.setImageCounts(value.size());
			mImageBean.setTopImagePath(value.get(0));//

			list.add(mImageBean);
		}

		return list;

	}
	
	
	
	protected void onActivityResult(int requestCode, int resultCode, Intent data){
		switch (requestCode) {	
		case RESULTE :
			if ( resultCode == RESULT_OK && null != data){
				mDrr = (List<String>)data.getSerializableExtra("selectedpath");
				Intent intent = new Intent();
				intent.putStringArrayListExtra("selectedpath", (ArrayList) mDrr);
				setResult(Activity.RESULT_OK,intent);
				MainActivity.this.finish();
			}
				
			
			break;
		}
	}

	
	}
